package peng.controller.admin;


import org.apache.commons.lang.StringUtils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import peng.bean.*;
import peng.controller.AppResult.ResultMessage;
import peng.entity.AdminUser;

import peng.entity.AdminUserGroup;
import peng.service.AdminUserGroupService;
import peng.service.AdminUserService;

import java.util.*;

/**
 * 后台管理
 */
@Controller
@RequestMapping("/admin")
public class AdminUserController {

    private final static String isdelete = "0";//初始化状态可用
    //private static String string = "bb";
    @Autowired
    private AdminUserService adminUserService;

    @Autowired
    private AdminUserGroupService adminUserGroupService;


    /**
     * 管理账户添加
     *  name account password sex（1男 0女） telphone
     * @param bg
     * @return
     */
    @RequestMapping("/add")
    @ResponseBody
    public ResultMessage add(AuserBridging bg) {
        AdminUser adminUser = new AdminUser();
        //adminUser.setId(1);
        if (bg == null){
            return new ResultMessage(ResultMessage.code_FAIL_0,"异常");
        }
        if (StringUtils.isEmpty(bg.getAccount())){
            return new ResultMessage(ResultMessage.code_FAIL_0,"用户名不能为空");
        }
        if (StringUtils.isEmpty(bg.getPassword())){
            return new ResultMessage(ResultMessage.code_FAIL_0,"密码不能为空");
        }
        if (bg.getRoleId()==null){
            return new ResultMessage(ResultMessage.code_FAIL_0,"异常");
        }
        int count =adminUserService.selectAccount(bg.getAccount());
        if ( count > 0){
            return new ResultMessage(ResultMessage.code_FAIL_0,"账号已存在");
        }else {
            adminUser.setName(bg.getName());
            adminUser.setAccount(bg.getAccount());
            String md5Code = GeneratePass.encode(bg.getPassword());
            adminUser.setPassword(md5Code);
            adminUser.setSex(bg.getSex());
            adminUser.setTelphone(bg.getTelphone());
            adminUser.setRoleId(bg.getRoleId());
            adminUser.setIsDelete(isdelete);
            adminUser.setStatus(isdelete);
            adminUser.setDescription(bg.getDescription());
            adminUser.setCreateTime(new Date());
            int i = adminUserService.insertSelective(adminUser);
            if (i > 0){
                return new ResultMessage(ResultMessage.code_OK_1,"成功");
            }else{
                return new ResultMessage(ResultMessage.code_FAIL_0,"不成功");
            }
        }

    }

    /**
     * 登录
     * accountOrphone =  telphone or Account 账号登录
     * password = 密码
     * @return id name account sex telphone group_name description
     *
     */
    @RequestMapping("/login")
    @ResponseBody
    public ResultMessage login(adminLogin login){
        if (login == null){
            return new ResultMessage(ResultMessage.code_FAIL_0,"异常");
        }
        if (StringUtils.isEmpty(login.getAccountOrphone()) || StringUtils.isEmpty(login.getPassword())){
            return new ResultMessage(ResultMessage.code_FAIL_0,"账号密码不为空");
        }
        //判断是否有此账户
        int i =adminUserService.selectAccount(login.getAccountOrphone());
        if (i<=0) {
            return new ResultMessage(ResultMessage.code_FAIL_0,"账号或密码错误");
        }
        AdminUser adminUser = adminUserService.selectByAdminAndPass(login.getAccountOrphone());
        //判断账户可用否
        if (adminUser.getStatus().equals(ResultMessage.code_status_NO)){
            return new ResultMessage(ResultMessage.code_FAIL_0,"账户已禁用，联系管理员");
        }
        //密码验证
        String pass = GeneratePass.encode(login.getPassword());
        if (pass.equals(adminUser.getPassword())){
            Map usermap = new HashMap();
            usermap.put("id",adminUser.getId());
            usermap.put("name",adminUser.getName());
            usermap.put("account",adminUser.getAccount());
            usermap.put("sex",adminUser.getTelphone() == "1" ? "男":"女");
            usermap.put("telphone",adminUser.getTelphone());
            String groupname=adminUserGroupService.selectByPrimaryKey(adminUser.getRoleId()).getName();
            usermap.put("group_name",groupname);
            usermap.put("description",adminUser.getDescription());
            return new ResultMessage(ResultMessage.code_FAIL_0,"成功",usermap);
        }
        return new ResultMessage(ResultMessage.code_FAIL_0,"账号或密码错误");
    }

    /**
     * 基本信息更新
     *  name sex telphone
     *
     * @return
     * 第一步，根据用户的ID查找当前修改的用户
     * 第二步，根据修改的信息，对原来用户的信息进行修改赋值（只修改要修改的字段信息【加判断】）
     * 第三步，更新的操作
     */
    @RequestMapping("/update")
    @ResponseBody
    public ResultMessage updateData(AuserBridging user){

        if (user.getId() == null || user.getId().intValue() == 0){
            return new ResultMessage(ResultMessage.code_FAIL_0,"异常");
        }
        //判断id是否正确
        if (adminUserService.selectByid(user.getId()) == 0){
            return new ResultMessage(ResultMessage.code_FAIL_0,"异常");
        }
        //判断更新的手机号是否存在
        if (adminUserService.selectAccount(user.getTelphone())>0){
            return new ResultMessage(ResultMessage.code_FAIL_0,"telphone已存在");
        }
        AdminUser adminUser = adminUserService.selectByPrimaryKey(user.getId());
        //赋值
        adminUser.setName(user.getName());
        adminUser.setTelphone(user.getTelphone());
        adminUser.setUpdateTime(new Date());
       int i= adminUserService.updateByPrimaryKeySelective(adminUser);
       if (i>0) {
           return new ResultMessage(ResultMessage.code_OK_1, "成功");
       }
       return new ResultMessage(ResultMessage.code_FAIL_0,"失败");

    }
    /**
     * 校验用户名 or phone是否重复
     * accountOrphone  账户 or phone
     */
    @RequestMapping("/testing")
    @ResponseBody

    public ResultMessage testing(String accountOrphone){
        if (StringUtils.isEmpty(accountOrphone)){
            return new ResultMessage(ResultMessage.code_FAIL_0,"异常");
        }
        int count =adminUserService.selectAccount(accountOrphone);
        if ( count> 0){
            return new ResultMessage(ResultMessage.code_FAIL_0,"账户已存在");
        }else {
            return new ResultMessage(ResultMessage.code_OK_1, "此账号可用");
        }
    }


    /**
     * 条件查询 或 不加条件 查询所有
     * @return id name account sex telphone roleId status description
     *currentPage 当前页码,用户传入
     *pageSize 每页的记录数
     * prevPage 上一页
     * nextPage 下一页
     * totalCount 总条数
     * totalPage 总页数
     */
    @RequestMapping("/selectQuery")
    @ResponseBody
    public ResultMessage queryselect(PageBeanAdmin vo){
        PageResult pageResult = adminUserService.queryselect(vo);
        return new ResultMessage(ResultMessage.code_FAIL_0,"成功",pageResult);
    }
    /**
     * 分组下拉框
     */
    @RequestMapping("/groupList")
    @ResponseBody
    public ResultMessage groupList(){
        List<AdminUserGroup> adminGroup = adminUserGroupService.selectAll();
        List grouplist = new ArrayList();
        for (AdminUserGroup adminUserGroup:adminGroup){
            Map groupmap = new HashMap();
            groupmap.put("id",adminUserGroup.getId());
            groupmap.put("name",adminUserGroup.getName());
            grouplist.add(groupmap);

        }
        return new ResultMessage(ResultMessage.code_OK_1,"成功",grouplist);

    }    /**
     * 删除管理员
     */
    @RequestMapping("/delete")
    @ResponseBody
    public ResultMessage admindelete(Integer id){
        if (adminUserService.selectByid(id) == 0){
            return new ResultMessage(ResultMessage.code_FAIL_0,"异常");
        }
        AdminUser adminUser = new AdminUser();
        adminUser.setId(id);
        adminUser.setIsDelete(ResultMessage.code_delete_OK);
        adminUser.setStatus(ResultMessage.code_status_NO);
        if (adminUserService.updateByPrimaryKeySelective(adminUser)>0){
            return new ResultMessage(ResultMessage.code_OK_1,"成功");
        }else {
            return new ResultMessage(ResultMessage.code_FAIL_0,"失败");
        }
    }
    /**
     * 修改密码
     */
    @RequestMapping("/updatepawd")
    @ResponseBody
    public ResultMessage updatePass(UpdataPawd updataPawd){
        if (StringUtils.isEmpty(updataPawd.getOldPwsd()) || StringUtils.isEmpty(updataPawd.getNewPwsd())){
            return new ResultMessage(ResultMessage.code_FAIL_0,"原密码和新密码不为空");
        }

        AdminUser adminUser = adminUserService.selectByPrimaryKey(updataPawd.getId());
        //System.out.println("---------------------"+adminUser.getPassword());
        //System.out.println("======================="+GeneratePass.encode(updataPawd.getOldPwsd()));
        if (GeneratePass.encode(updataPawd.getOldPwsd()).equals(adminUser.getPassword())){
            if (updataPawd.getNewPwsd().equals(updataPawd.getConfirmPwsd())){
                adminUser.setPassword(GeneratePass.encode(updataPawd.getNewPwsd()));
                if (adminUserService.updateByPrimaryKeySelective(adminUser)>0){
                    return new ResultMessage(ResultMessage.code_OK_1,"成功");
                }else {
                    return new ResultMessage(ResultMessage.code_FAIL_0,"失败");
                }

            }

        }else {
        return new ResultMessage(ResultMessage.code_FAIL_0,"原始密码不正确");
        }
        return new ResultMessage(ResultMessage.code_FAIL_0,"两次密码不一致");

    }
    /***
     * 禁用状态编辑
     * status 1 可用  0不可用
     */
    @RequestMapping("/status")
    @ResponseBody
    public ResultMessage status(Integer id,String status){

        if (adminUserService.selectByid(id) == 0){
            return new ResultMessage(ResultMessage.code_FAIL_0,"异常");
        }
        AdminUser adminUser = adminUserService.selectByPrimaryKey(id);
        adminUser.setStatus(status);
        if (adminUserService.updateByPrimaryKeySelective(adminUser)>0){
            return new ResultMessage(ResultMessage.code_OK_1,"成功");
        }
        return new ResultMessage(ResultMessage.code_FAIL_0,"异常");
    }
    /***
     * 设置分组和描述
     * id 用户id
     * roleId 分组id
     * description 描述
     */

    @RequestMapping("/SetGroups")
    @ResponseBody
    public ResultMessage SettingGroups(Integer id,Integer roleId,String description){
        if (id == null || id.intValue() == 0){
            return new ResultMessage(ResultMessage.code_FAIL_0,"异常");
        }

        int y = adminUserService.selectByid(id);
        if (y == 0){
            return new ResultMessage(ResultMessage.code_FAIL_0,"异常");
        }
        AdminUser adminUser = adminUserService.selectByPrimaryKey(id);
        adminUser.setRoleId(roleId);
        adminUser.setDescription(description);
        int i = adminUserService.updateByPrimaryKeySelective(adminUser);
        if (i>0){
            return new ResultMessage(ResultMessage.code_OK_1,"成功");
        }
        return  new ResultMessage(ResultMessage.code_FAIL_0,"失败");
    }
}
